import React, { useEffect, useRef } from 'react';
import cn from 'classnames';
import BreadCrumb from '@/components/BreadCrumb';
import { Table, Input, Dialog, Message, Icon, Tooltip, Loading, Form, Button } from '@knownsec/react-component';
import i from '@/index.module.css';
import c from '@/common.module.css';
import s from '../style.module.css';
import { modifySysConfig, modifySysPing, modifySysMode } from '~/API/index';
import { getErrorMessage } from '@/common/constant';

const spans = () => {
  return (
    <>
      <span className={i.vam}>网口用途</span>
    </>
  );
};
export default function NetworkConfig() {
  const [configData, setConfigData] = React.useState({
    ports: [],
    primary_dns: '',
    secondary_dns: '',
    system_mode: null,
  });
  const [pingVisible, setPingVisible] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [pingData, setPingData] = React.useState([]);
  const updateForm = useRef();
  const [updateVisible, setUpdateVisible] = React.useState(false);
  const [updateData, setUpdataData] = React.useState({
    name: '',
    type: '',
    ipv4_addr: '',
    ipv4_netmask: '',
    ipv4_gateway: '',
    status: 0,
  });
  useEffect(() => {
    getConfigData();
  }, []);
  const getConfigData = () => {
    setLoading(true);
    modifySysConfig('GET').then((res) => {
      setLoading(false);
      if (res.status === 'success') {
        const ports = res.data.ports.map((item) => {
          item.modify = item.name;
          return item;
        });
        setConfigData({ ...res.data, ports });
      }
    });
  };
  const submitUpdateConfig = () => {
    updateForm.current.validateFields().then((res) => {
      modifySysConfig('POST', { tag: 'network', ...res })
        .then((res) => {
          if (res.status === 'success') {
            Message.show({
              pro: true,
              type: 'success',
              message: '修改成功',
              onclose: () => {
                setUpdateVisible(false);
                getConfigData();
              },
            });
          }
        })
        .catch((err) => {
          Message.show({
            type: 'error',
            message: getErrorMessage(err, 'data'),
          });
        });
    });
  };
  const testPing = (name, item) => {
    // if (!configData.system_mode) {
    //   return Message.show({
    //     type: 'error',
    //     message: '请先选择运行模式',
    //   });
    // }
    setLoading(true);
    modifySysPing({ name }).then((res) => {
      setLoading(false);
      if (res.status === 'success') {
        setPingVisible(true);
        const map = Object.keys(res.data).reduce((t, i) => {
          t[i] = { status: res.data[i], label: i === item.ipv4_addr ? 'IPv4地址' : i === item.ipv4_gateway ? 'IPv4网关' : 'DNS' }
          return t
        }, {})
        setPingData(map);
      }
    });
  };
  const columns = [
    { title: '网口名称', key: 'name', dataIndex: 'name' },
    {
      title: spans(),
      key: 'type',
      dataIndex: 'type',
      render: (cur) => {
        return (
          <>
            <span className={cn(i.dib, i.vam)}>{cur === 'work' ? '工作口' : cur === 'bypass' ? 'bypass口' : '管理口'}</span>
            {(cur === 'work' || cur === 'mgmt') && (
              <Tooltip
                overlay={
                  cur === 'work'
                    ? '工作口用于平台正常工作'
                    : cur === 'mgmt'
                      ? '管理口用于对设备进行管理'
                      : ''
                }
                placement={'top'}
              >
                <Icon type="question" className={cn(i.mainColor, i.ml5, i.vam, i.cp)} />
              </Tooltip>
            )}
          </>
        );
      },
    },
    { title: 'IPv4地址', key: 'ipv4_addr', dataIndex: 'ipv4_addr' ,render:(e)=>{return e||'--'}},
    { title: 'IPv4网络掩码', key: 'ipv4_netmask', dataIndex: 'ipv4_netmask' ,render:(e)=>{return e||'--'}},
    { title: 'IPv4网关', key: 'ipv4_gateway', dataIndex: 'ipv4_gateway' ,render:(e)=>{return e||'--'}},
    { title: 'IPv6地址', key: 'ipv6_addr', dataIndex: 'ipv6_addr',render:(e)=>{return e||'--'} },
    { title: 'IPv6前缀', key: 'ipv6_netmask', dataIndex: 'ipv6_netmask' ,render:(e)=>{return e||'--'}},
    { title: 'IPv6网关', key: 'ipv6_gateway', dataIndex: 'ipv6_gateway' ,render:(e)=>{return e||'--'}},
    {
      title: '操作',
      key: 'modify',
      dataIndex: 'modify',
      render: (cur, item) => {
        return (
          <>
            {!item.editable ? (
              <>
                <span className={cn(i.mainColor, i.cp)} onClick={() => testPing(cur, item)}>
                  测试
                </span>
              </>
            ) : (
              <>
                <>
                  <span
                    className={cn([i.cp, i.mainColor])}
                    onClick={() => {
                      // if (configData.system_mode !== 'proxy') return;
                      updateForm.current.setFieldsValue({
                        ...item,
                        ipv6_addr: item.ipv6_addr || '',
                        ipv6_gateway: item.ipv6_gateway || '',
                        ipv6_netmask: item.ipv6_netmask || '',
                      });
                      setUpdataData(item);
                      setUpdateVisible(true);
                    }}
                  >
                    编辑
                  </span>
                  <span
                    className={cn(i.ml20, [i.cp, i.mainColor])}
                    onClick={() => {
                      testPing(cur, item);
                    }}
                  >
                    测试
                  </span>
                </>
              </>
            )}
          </>
        );
      },
    },
  ];
  return (
    <div className={i.mainContent}>
      <BreadCrumb
        arr={[
          { link: '', name: '网络配置' },
          { link: '', name: '网口配置', active: true },
        ]}
      />
      <div className={cn(s.content, i.p24, i.oa, i.h100p, i.mins)}>
        <div className={s.bgc}>
          <div className={cn(i.p24, i.pr)}>
            {/* <Loading show={loading} /> */}
            <p>网口配置</p>
            <div className={i.pt20}>
              <Table columns={columns} data={configData.ports} tableLoading={loading} loadingLabel="" />
            </div>
          </div>
        </div>
      </div>
      <Dialog
        title="编辑网络配置"
        className={s.w570}
        visible={updateVisible}
        // cancelText="取消"
        cusCancel={<Button type="default" className={i.mr30} onClick={() => {
          updateForm.current.resetFields();
          setUpdateVisible(false);
        }}>取消</Button>}
        confirmText="确认"
        onsubmit={submitUpdateConfig}
        onhide={() => {
          updateForm.current.resetFields();
          setUpdateVisible(false);
        }}
      >
        <div className={cn(i.pt20, i.pl30, i.pr30)} style={{ maxHeight: '60vh', overflow: 'auto' }}>
          <Form
            className={s.updateForm}
            colon={false}
            initialValues={updateData}
            ref={updateForm}
            onValuesChange={(newItem) => {
              const values = Object.keys(newItem).reduce((total, key) => {
                total[key] = newItem[key].value;
                return total;
              }, {});
              updateForm.current.setFieldsValue(values);
            }}
          >
            <Form.Item label="网口名称" name="name">
              <Input pro className={cn(i.flex1, i.cna)} disabled />
            </Form.Item>
            <Form.Item label="网口用途" name="type">
              <div className={cn(i.bd, i.pt8, i.pl16, i.pb8, i.flex1, s.disabled, s.nbor)}>
                {updateData.type === 'work'
                  ? '工作口': '管理口'}
              </div>
            </Form.Item>
            <Form.Item
              label="IPv4地址"
              name="ipv4_addr"
              rules={[{ required: true, message: '请填写IPv4地址' }]}
            >
              <Input pro className={cn(i.flex1)} />
            </Form.Item>
            <Form.Item
              label="IPv4网络掩码"
              name="ipv4_netmask"
              rules={[{ required: true, message: '请填写IPv4网络掩码' }]}
            >
              <Input pro className={cn(i.flex1)} />
            </Form.Item>
            <Form.Item
              label="IPv4网关"
              name="ipv4_gateway"
              rules={[{ required: true, message: '请填写IPv4网关' }]}
            >
              <Input pro className={cn(i.flex1)} />
            </Form.Item>
            <Form.Item label="IPv6地址" name="ipv6_addr">
              <Input pro className={cn(i.flex1)} />
            </Form.Item>
            <Form.Item label="IPv6前缀" name="ipv6_netmask">
              <Input pro className={cn(i.flex1)} />
            </Form.Item>
            <Form.Item label="IPv6网关" name="ipv6_gateway">
              <Input pro className={cn(i.flex1)} />
            </Form.Item>
          </Form>
        </div>
      </Dialog>
      <Dialog
        title="测试网络"
        className={s.w500}
        visible={pingVisible}
        cusCancel={<Button className={i.mr30} type="default" onClick={() => {
          setPingVisible(false)
        }}>取消</Button>}
        confirmText="确认"
        onsubmit={() => setPingVisible(false)}
        onhide={() => setPingVisible(false)}
      >
        <div className={cn(i.pt20, i.pb20, i.pl30, i.pr30)}>
          <p className={cn(i.primaryColor)}>可测试你当前的网络配置是否正确</p>
          <div className={cn(i.bd, i.pb20, i.mt16, s.testColor)}>
            {Object.keys(pingData).map((key) => (
              <div className={cn(i.pt20, i.pr10, i.pl10, c.df, c.aic)}>
                <span className={cn(c.tar, c.mr10, c.w80)}>{pingData[key].label}：</span><span>Ping {key} - {pingData[key].status ? 'ok' : 'fail'}</span>
              </div>
            ))}
          </div>
        </div>
      </Dialog>
    </div>
  );
}
